<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card style="margin: 20px auto;">
      <el-alert title="编辑商品信息" type="info" center show-icon :closable="false"></el-alert>
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品种类"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
    </el-card>

    <!-- 表单 -->
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" label-position="left">
      <el-tabs :tab-position="'left'" v-model="activeIndex">
        <el-tab-pane label="基本信息" name="1">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="副标题" prop="subTitle">
            <el-input v-model="editForm.subTitle" type="textarea"></el-input>
          </el-form-item>
          <div class="input-box">
            <el-form-item label="商品价格" prop="price">
              <el-input v-model.number="editForm.price" type="number" placeholder="请输入商品价格" />
            </el-form-item>
            <el-form-item label="商品数量" prop="stock">
              <el-input v-model.number="editForm.stock" type="number"></el-input>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch v-model="editForm.status" />
            </el-form-item>
            <el-form-item label="是否热门">
              <el-switch v-model="editForm.hotFlag" />
            </el-form-item>
          </div>
        </el-tab-pane>

        <el-tab-pane label="商品图片" name="3">
          <ProductImage
              @mainImage="handleUpdateMainImage"
              @subImages="handleUpdateSubImages"
              :initialMainImage="editForm.mainImage"
              :initialSubImages="editForm.subImages"
          />
        </el-tab-pane>
        <el-tab-pane label="商品详情" name="4">
          <ProductDetail @vHtml="handleUpdateDetail" />
        </el-tab-pane>
        <el-tab-pane label="提交内容" name="5">
          <ProductPreview :form="editForm" />
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <div class="btn-group" v-if="activeIndex == 5">
      <el-button type="primary" @click="commitForm">提交修改</el-button>
      <el-button @click="resetForm">重置表单</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getproduct, updateProduct, getCategories, getSubCategories } from "@/apis/product";
import ProductParam from "./ProductParam.vue";
import ProductImage from "./ProductImage.vue";
import ProductDetail from "./ProductDetail.vue";
import ProductPreview from "./ProductPreview.vue";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();

const productId = route.params.id; // 获取路由中的商品 ID
const activeIndex = ref(0);

const editForm = reactive({
  id: null, // 确保保存商品 ID
  name: "",
  price: null,
  subTitle: "",
  stock: null,
  categoryId: null,
  subCategoryId: null,
  mainImage: "",
  subImages: [],
  param: [],
  detail: "",
  hotFlag: false,
  status: true,
});

const editFormRef = ref(null);
const categories = ref([]);
const subCategories = ref([]);

// 表单验证规则
const editFormRules = ref({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  price: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
    { type: "number", message: "商品价格必须为数字", trigger: "blur" },
  ],
  stock: [
    { required: true, message: "请输入商品数量", trigger: "blur" },
    { type: "number", message: "商品数量必须为数字", trigger: "blur" },
  ],
});

// 处理图片更新
const handleUpdateMainImage = (newMainImage) => {
  editForm.mainImage = newMainImage;
};
const handleUpdateSubImages = (newSubImages) => {
  editForm.subImages = newSubImages;
};

// 处理商品详情更新
const handleUpdateDetail = (newDetail) => {
  editForm.detail = newDetail;
};

// 分类相关操作
const setSubCategories = async (categoryId) => {
  const res = await getSubCategories(categoryId);
  subCategories.value = res;
};

// 提交表单
const commitForm = () => {
  editFormRef.value.validate((valid, fields) => {
    if (valid) {
      updateProduct(editForm)
          .then(() => {
            ElMessage.success("修改成功");
            router.push("/admin/product");
          })
          .catch((err) => {
            console.error(err);
            ElMessage.error("修改失败，请稍后再试");
          });
    } else {
      const firstErrorField = Object.keys(fields)[0];
      const firstErrorMessage = fields[firstErrorField][0].message;
      ElMessage.error(`错误提示: ${firstErrorMessage}`);
    }
  });
};

// 重置表单
const resetForm = () => {
  editFormRef.value.resetFields();
  activeIndex.value = 0;
};

// 加载商品信息
const loadProduct = async () => {
  try {
    const res = await getproduct(productId); // 获取商品信息
    Object.assign(editForm, res); // 填充商品信息
    editForm.id = productId; // 确保 ID 被赋值
    await loadCategories();
    if (editForm.categoryId) {
      await setSubCategories(editForm.categoryId);
    }
  } catch (error) {
    ElMessage.error("获取商品信息失败");
  }
};

// 加载分类信息
const loadCategories = async () => {
  const res = await getCategories();
  categories.value = res;
};

onMounted(() => {
  loadProduct();
});
</script>

<style scoped lang="scss">
.el-steps {
  margin: 15px 0;
}

.el-step__title {
  font-size: 13px;
}

.category .el-select {
  width: 50%;
}

.input-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}
</style>
